package com.jialiang.yojcodesandbox.feign;

import com.jialiang.yojcodesandbox.enums.QuestionSubmitLanguageEnum;
import com.jialiang.yojcodesandbox.model.ExecuteCodeRequest;
import com.jialiang.yojcodesandbox.model.ExecuteCodeResponse;
import com.jialiang.yojcodesandbox.service.CodeSandbox;
import com.jialiang.yojcodesandbox.service.factory.CodeSandboxFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController()
@RequestMapping("/rpc")
public class SandboxClient {
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                    HttpServletRequest request, HttpServletResponse response) {
        log.info("沙箱请求数据：" + executeCodeRequest);
        if (executeCodeRequest == null ||
                executeCodeRequest.getCode() == null ||
                executeCodeRequest.getInputList() == null ||
                executeCodeRequest.getLanguage() == null) {
            response.setStatus(400);
            log.info("沙箱请求参数为空，拒接请求");
            return null;
        }
        // 调用原生代码沙箱
        // ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(executeCodeRequest.getLanguage());
        CodeSandbox codeSandbox = CodeSandboxFactory.getInstance(languageEnum);
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        log.info("沙箱响应信息：{}", executeCodeResponse);
        return executeCodeResponse;
    }

}
